#include "texture.hpp"
#include "surface.hpp"
#include <SDL_Image.h>

namespace yep
{
Texture::Texture(SDL_Surface *surface_)
{
	surface = SDL_DisplayFormatAlpha(surface_);
}

Texture::Texture(SDL_RWops *loadFrom, bool freesrc)
{
	SDL_Surface *temp = IMG_Load_RW(loadFrom, freesrc);
	surface = SDL_DisplayFormatAlpha(temp);
	SDL_FreeSurface(temp);
}

Texture::Texture(const string &file)
{
	SDL_Surface *temp = IMG_Load(file.c_str());
	if (temp == NULL)
	{
		cerr << IMG_GetError() << endl;
		exit(EXIT_FAILURE);
	}
	surface = SDL_DisplayFormatAlpha(temp);
	SDL_FreeSurface(temp);
}

Texture::Texture(const Surface &surface_)
{
	surface = SDL_DisplayFormatAlpha(surface_.getSurface());
}

Texture::Texture(const Texture &texture)
{
	surface = texture.surface;
	++surface->refcount;
}

Texture::~Texture()
{
	SDL_FreeSurface(surface);
}

void Texture::draw(Canvas &canvas, const Vector2 &position)
{
	SDL_BlitSurface(surface, NULL, canvas.getSurface(), position);
}

void Texture::draw(Canvas &canvas, const Vector2 &position,
		const Vector2 &sectionPosition, const Vector2 &sectionSize)
{
	SDL_Rect section
	{ (Sint16) sectionPosition.x, (Sint16) sectionPosition.y,
			(Uint16) sectionSize.x, (Uint16) sectionSize.y };
	SDL_BlitSurface(surface, &section, canvas.getSurface(), position);
}

}
